//
//  WZDoingController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/7/11.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZDoingController.h"
#import "WZDetailTask.h"
#import "CFolderMgr.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "CAccountModel.h"
#import "WZProgressViewController.h"
#import "WZDelayDetailViewController.h"
#import "WZTaskLogController.h"
#import "JKAlertDialog.h"

#define TaskManager_Detail_Finished_Message @"确认提交完成申请?"
#define TaskManager_Detail_Finished_Cancel  @"取消"
#define TaskManager_Detail_Finished_Done    @"确定"
#define TaskManager_Detail_Unfinished       @"进度未达到100%"
#define TaskManager_Detail_Finished_Success @"提交成功"

typedef enum : NSUInteger {
    DoingVcUpdateButtonTag = 8000,
    DoingVcDelayButtonTag,
    DoingVcDoneButtonTag,
} DoingVcButtonTag;


@interface WZDoingController ()<UIAlertViewDelegate,UIActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UILabel *taskName;
@property (weak, nonatomic) IBOutlet UILabel *desc;
@property (weak, nonatomic) IBOutlet UILabel *beginTime;
@property (weak, nonatomic) IBOutlet UILabel *endTime;
@property (weak, nonatomic) IBOutlet UILabel *projectName;
@property (weak, nonatomic) IBOutlet UILabel *statusName;
@property (weak, nonatomic) IBOutlet UILabel *progress;
@property (weak, nonatomic) IBOutlet UILabel *exturoName;
@property (weak, nonatomic) IBOutlet UILabel *assignerName;

@property (nonatomic, strong) WZDetailTask  *detailTask;
@property (nonatomic, strong) CContactModel *curAccount;
@property (nonatomic, strong) CAccountModel *acc;

@property (nonatomic, weak) UIButton *updateBtn;
@property (nonatomic, weak) UIButton *doneBtn;
@property (nonatomic, weak) UIButton *delayBtn;


@end

@implementation WZDoingController

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    [self getTaskDetailInfor];
    
}


- (void)setupTableView {
    
    self.tableView.backgroundColor = WZRGBColor(245, 246, 249);
    self.title = @"任务详情";
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.tableView.tableFooterView.backgroundColor = [UIColor greenColor];
    
    UIButton *updateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.updateBtn = updateBtn;
    [updateBtn setTitle:@"更新" forState:UIControlStateNormal];
    updateBtn.backgroundColor = WZRGBColor(247, 187, 66);
    updateBtn.frame = CGRectMake(1.5, HARDWARE_SCREEN_HEIGHT - 44 - 64, HARDWARE_SCREEN_WIDTH / 3 - 2, 44);
    [updateBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:updateBtn];
    updateBtn.tag = DoingVcUpdateButtonTag;
    
    
    UIButton *delayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.delayBtn = delayBtn;
    [delayBtn setTitle:@"延期" forState:UIControlStateNormal];
    delayBtn.backgroundColor = WZRGBColor(94, 196, 206);
    delayBtn.frame = CGRectMake(CGRectGetMaxX(updateBtn.frame) +  1.5,  HARDWARE_SCREEN_HEIGHT - 44 - 64, HARDWARE_SCREEN_WIDTH / 3 - 2, 44);
    [delayBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:delayBtn];
    delayBtn.tag = DoingVcDelayButtonTag;
    
    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.doneBtn = doneBtn;
    [doneBtn setTitle:@"完成" forState:UIControlStateNormal];
    doneBtn.backgroundColor = WZRGBColor(94, 196, 206);
    doneBtn.frame = CGRectMake(CGRectGetMaxX(delayBtn.frame) + 1.5, HARDWARE_SCREEN_HEIGHT - 44 -64, HARDWARE_SCREEN_WIDTH / 3 - 2, 44);
    [doneBtn addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:doneBtn];
    doneBtn.tag = DoingVcDoneButtonTag;
    
    
//    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
//    self.acc = acc;
//    self.curAccount = [[[CContactMgr alloc] init] loadContactWithUserCode:acc.userName];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.scrollEnabled = NO;
    
}


/**任务详细信息*/
- (void)getTaskDetailInfor {
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"name"] = self.oaUserName;
    params[@"pwd"] = self.oaPwd;
    params[@"taskId"] = self.taskId;
    
    [NetWorkShare getTaskDetailInforWithParams:params SuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                
                _detailTask = [WZDetailTask objectWithKeyValues:responseObject[@"detail"]];
                
                [self loadData];
                
                // 知会我的
                if (![self.oaUserId isEqualToString:self.detailTask.executorId] && ![self.oaUserId isEqualToString:self.detailTask.assignerId]) {
                    
                    self.updateBtn.hidden = YES;
                    self.delayBtn.hidden = YES;
                    self.doneBtn.hidden = YES;
//                    self.doneBtn.hidden = [self.statusName.text isEqualToString:@"待审核"];
                 
                    // 我是分配人不是执行者
                } else if ([self.oaUserId isEqualToString:self.detailTask.assignerId] && ![self.oaUserId isEqualToString:self.detailTask.executorId]) {
                    
                    self.updateBtn.hidden = YES;
                    self.delayBtn.hidden = YES;
                    self.doneBtn.hidden = YES;
//                    self.doneBtn.hidden = [self.statusName.text isEqualToString:@"待审核"];
                
                    // 我是执行者不是分配者
                } else if (![self.oaUserId isEqualToString:self.detailTask.assignerId] && [self.oaUserId isEqualToString:self.detailTask.executorId]) {
                    
                    self.updateBtn.hidden = NO;
                    self.delayBtn.hidden = NO;
                    self.doneBtn.hidden = NO;
                    
                    // 执行和分配是同一个人
                } else if ([self.oaUserId isEqualToString:self.detailTask.assignerId] && [self.oaUserId isEqualToString:self.detailTask.executorId]) {
                    
                    self.updateBtn.hidden = NO;
                    self.delayBtn.hidden = NO;
                    self.doneBtn.hidden = NO;
                    
                }
                
                if ([_detailTask.statusName isEqualToString:@" 未开始"]) {
                    
                    _doneBtn.enabled = NO;
                    _doneBtn.backgroundColor = WZRGBColor(204, 207, 218);
                    
                } else {
                    
                    _doneBtn.enabled = YES;
                    _doneBtn.backgroundColor = WZRGBColor(94, 196, 206);
                }
                
                if ([_detailTask.statusName isEqualToString:@"待审核"] && [self.progress.text isEqualToString:@"100"]) {
                    
                    _delayBtn.enabled = NO;
                    _delayBtn.backgroundColor = WZRGBColor(204, 207, 218);
                    
                    _updateBtn.enabled = NO;
                    _updateBtn.backgroundColor = WZRGBColor(204, 207, 218);
                    
                    _doneBtn.enabled = NO;
                    _doneBtn.backgroundColor = WZRGBColor(204, 207, 218);
                    
                } else if ([_detailTask.statusName isEqualToString:@"待审核"]) {
                   
                    _delayBtn.enabled = NO;
                    _delayBtn.backgroundColor = WZRGBColor(204, 207, 218);
                    
                } else {
                    
                    _delayBtn.enabled = YES;
                    _delayBtn.backgroundColor = WZRGBColor(94, 196, 206);
                }
                
                if ([_detailTask.statusName isEqualToString:@"实施中"]) {
                    
                    _doneBtn.enabled = YES;
                    _doneBtn.backgroundColor = WZRGBColor(94, 196, 206);
                    
                    _delayBtn.enabled = YES;
                    _delayBtn.backgroundColor = WZRGBColor(94, 196, 206);
                    
                    _updateBtn.enabled = YES;
                    _updateBtn.backgroundColor = WZRGBColor(247, 187, 66);
                }
                
                if ([_detailTask.statusName isEqualToString:@"已完成"] || [_detailTask.statusName isEqualToString:@"已终止"]) {
                    
                    self.updateBtn.hidden = YES;
                    self.delayBtn.hidden = YES;
                    self.doneBtn.hidden = YES;
                }
                
                [self.tableView reloadData];
                
                WZLog(@"%@", responseObject);
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
        } else {
            
            [MBProgressHUD showError:UNKNOWNERROR];
        }
    } FailureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUD];
        [self.view setHidden:YES];
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"error = %@", error);
    }];
    
}


#pragma mark - 完成任务
- (void)finishedTask {
    
    [MBProgressHUD showMessage:@"提交中..." toView:self.view];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"name"] = self.oaUserName;
    params[@"pwd"] = self.oaPwd;
    params[@"taskId"] = self.taskId;
    
    [NetWorkShare finishedTaskWithParams:params SuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([responseObject objectForKey:@"success"]) {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showSuccess:TaskManager_Detail_Finished_Success];
        }
        
    } FailureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:NETWORKNERROR];
    }];
}

- (void)btnDidClick:(UIButton *)sender {
    
    switch (sender.tag) {
        case DoingVcUpdateButtonTag:
        {
            WZProgressViewController *progressVc = [[WZProgressViewController alloc] init];
            progressVc.oaUserId = self.oaUserId;
            progressVc.oaUserName = self.oaUserName;
            progressVc.taskId = self.taskId;
            progressVc.oaPwd = self.oaPwd;
            progressVc.oaCompanyID = self.oaCompanyID;
            progressVc.progress = self.progress.text;
            progressVc.detailTask = self.detailTask;
            progressVc.block = ^(NSString *progress) {
                
                self.progress.text = progress;
                [self.tableView reloadData];
            };
            
            [self.navigationController pushViewController:progressVc animated:YES];
        }
            break;
            
        case DoingVcDelayButtonTag:
//        case DoingVcDoneButtonTag:
            
        {
            
            WZDelayDetailViewController *delayDetailVc = [[WZDelayDetailViewController alloc] init];
            delayDetailVc.oaUserId = self.oaUserId;
            delayDetailVc.oaUserName = self.oaUserName;
            delayDetailVc.taskId = self.taskId;
            delayDetailVc.oaPwd = self.oaPwd;
            delayDetailVc.oaCompanyID = self.oaCompanyID;
            delayDetailVc.detailTask = self.detailTask;
            delayDetailVc.block = ^(NSString *dateStr){
                
                self.endTime.text = dateStr;
                [self.tableView reloadData];
            };
            
            [self.navigationController pushViewController:delayDetailVc animated:YES];
            
        }
            break;
    
            
        case DoingVcDoneButtonTag:
            
        {
            if ([self.progress.text isEqualToString:@"100"]) {
                
                [self addAlertView];
                
            } else {
                
                [MBProgressHUD showError:TaskManager_Detail_Unfinished];
            }
            
        }
            break;
            
        default:
            break;
    }
}


- (void)loadData {
    
    self.taskName.text = self.detailTask.taskName;
    self.desc.text = self.detailTask.remark;
    self.beginTime.text = self.detailTask.planExecBeginDate;
    self.endTime.text = self.detailTask.planExecEndDate;
    self.projectName.text = self.detailTask.projectName;
    self.exturoName.text = self.detailTask.executorName;
    self.assignerName.text = self.detailTask.assignerName;
    self.statusName.text = self.detailTask.statusName;
    self.progress.text = self.detailTask.progress;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (6 == indexPath.row) {
        
        WZTaskLogController *logVc = [[WZTaskLogController alloc] init];
        logVc.taskId = self.taskId;
        logVc.oaUserName = self.oaUserName;
        logVc.oaPwd = self.oaPwd;
        [self.navigationController pushViewController:logVc animated:YES];
    }
}


#pragma mark - alertView Delegate

- (void)alertViewCancel:(UIAlertView *)alertView {
    
    WZLog(@"cancel button click");
    
    // TODO: 弹窗取消按钮
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    WZLog(@"done button click");
    

}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    WZLog(@"alertView dismiiss");
    
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - 弹窗提醒

- (void)addAlertView {
    
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:TaskManager_Detail_Finished_Message];
    [alert addButton:Button_OK withTitle:TaskManager_Detail_Finished_Done handler:^(JKAlertDialogItem *item) {
        
        [self finishedTask];
        if (_block) {
            _block();
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [alert addButton:Button_CANCEL withTitle:TaskManager_Detail_Finished_Cancel handler:^(JKAlertDialogItem *item) {
        
        
    }];
    
    [alert show];
}


#pragma mark - setupAlertView

- (void)setupAlertView {
    
    // 弹框提醒
    if ([UIDevice currentDevice].systemVersion.doubleValue < 8.0) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"确定提交完成申请?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
    } else if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定提交完成申请?" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:0 handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        UIAlertAction *sureBtn = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
            
            [self finishedTask];
            [MBProgressHUD showSuccess:@"提交成功"];
            
        }];
        
        [alert addAction:cancelBtn];
        [alert addAction:sureBtn];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        
        WZLog(@"systemVersion == %f", [UIDevice currentDevice].systemVersion.doubleValue);
    }
    
    WZLog(@"完成申请");
}


-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    if (!isExistenceNetwork) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//<span style="font-family: Arial, Helvetica, sans-serif;">MBProgressHUD为第三方库，不需要可以省略或使用AlertView</span>
        hud.removeFromSuperViewOnHide =YES;
        hud.mode = MBProgressHUDModeText;
//        hud.labelText = NSLocalizedString(INFO_NetNoReachable, nil);
        hud.minSize = CGSizeMake(132.f, 108.0f);
        [hud hide:YES afterDelay:3];
        return NO;
    }
    
    return isExistenceNetwork;
}
@end
